<?php

class Login extends CI_Controller {

	function __construct()
	{
			parent::__construct();
			$this->load->library(array('encrypt', 'form_validation', 'session'));
			$this->load->model('mglobal');
			$this->load->model('musers');
			$this->load->model('mcluster');
			$this->load->helper('url');
			$this->load->helper('captcha');
			$this->load->model('mmaster');
			$this->config->load('custom_config', TRUE);
	}
	
	function index ($redirect = '')
	{

			// $session_expiration = $this->config->item('sess_expiration', 'custom_config');
			// $this->config->set_item('sess_expiration', $session_expiration);

			$is_logged_in = $this->session->userdata('is_logged_in');
			if($is_logged_in == true)
			{
				if ($redirect) {
					redirect($this->core->decode($redirect));
				} else {
					redirect('/main/welcome');                       
				}
			}
			
			####### proses login di sini
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required|callback_password_check');
			$this->form_validation->set_rules('ractha', 'Kode Validasi', 'required|callback_captcha_check');
					
			$this->form_validation->set_error_delimiters('<li>','</li>');
			$this->form_validation->set_message('required', 'Kolom %s harus diisi');
			
			$hasil = "";
			$username = $this->input->post('username');
			$jumlah_salah = "";
			if ($this->form_validation->run() != FALSE) {
					
					$userdata = array (
						'username'     => $username,
						'pwd'          => $this->input->post('password'),
						'group'        => $this->mglobal->showdata("user_group_id", "t_mtr_user", array("user_id"=>$username),"dblokal"),
						'jabatan'      => 'admin', //edited : alfin akhret
						'is_logged_in' => true,
						'cluster_id'   => $this->mglobal->user_cluster($username),
						'region_id'    => $this->mglobal->user_region($this->mglobal->user_cluster($username)),
					);
					$this->session->set_userdata($userdata);
					 //is_self_service //edited by Alfin Akhret
					$data2 = $this->mglobal->get_is_self_service($this->session->userdata('group'));
					$this->session->set_userdata(array('is_self_service' => $data2));  
					//------------------------------------------------------------------------------// 

					$this->mglobal->set_is_login(1);
					$this->musers->update_login_attemp($username,0);
					// redirect(base_url() . "index.php/main/welcome");

					//by : alfin akhret
					//check password expiration date
					$last_update_pwd = $this->mglobal->showdata('last_time_change_password','t_mtr_user',array('user_id'=>$this->input->post('username')),'dblokal');
					$rentang = $this->mglobal->showdata('lookup_value','t_mtr_lookup',array('lower(lookup_key)'=>'account_expired'),'dblokal');
					
					$last_update_pwd = strtotime($last_update_pwd);
					$rentang = $rentang*60*60*24;
					$expired_date = $last_update_pwd + $rentang;
					$expired_date = floor($expired_date/(60*60*24));
					$days = floor(strtotime(date("Y-m-d"))/(60*60*24));

					$pass_length = $this->mglobal->get_pass_length();
				  
					if(($days >= $expired_date) || strlen($this->input->post('password')) < $pass_length)
					{
						$this->mglobal->set_must_change_password($this->session->userdata('username'), '1');
					}
					else
					{
						$this->mglobal->set_must_change_password($this->session->userdata('username'), '0');
					}

					$ganti_password = $this->mglobal->showdata("must_change_password","t_mtr_user",array("user_id"=>$this->session->userdata('username')),"dblokal");
				 
					// if($ganti_password == 1 || strlen($this->session->userdata('pwd')) < 8 ){
					if($ganti_password == 1){
						redirect("/user_management/change_password");
					}
					else
					{
						if ($redirect) {
							redirect($this->core->decode($redirect));
						} else {
							redirect("/cluster");
						}
					}
			}
			else
			{
					if($username <>""){
							
							$istatus = $this->mglobal->showdata('istatus','t_mtr_user',array('user_id'=>$this->input->post('username')),'dblokal');
							
							$last_update_pwd = $this->mglobal->showdata('last_time_change_password','t_mtr_user',array('user_id'=>$this->input->post('username')),'dblokal');
							$rentang = $this->mglobal->showdata('lookup_value','t_mtr_lookup',array('lower(lookup_key)'=>'account_expired'),'dblokal');
							$expired_date = date('Y-m-d', strtotime('+'.$rentang.' days', strtotime($last_update_pwd)));
							$data['expired'] = "";
							
							if($istatus <> 1){
									$data['expired'] = 'Status Akun Anda tidak aktif, silakan hubungi Administrator';
							}
							// edited by: alfin akhret
							// validasi password expire date seharusnya dilakukan pada saat semua input sudah benar
							// the code below no longer needed
							// elseif(date("Y-m-d") >= $expired_date ){
							//         $data['expired'] = 'Akun Anda telah expired karena tidak mengganti password selama '.$rentang.' hari, silakan hubungi Admin.';
							// }
							else{
									#update jumlah salah dulu
									$jumlah_salah = $this->mglobal->showdata('logon_attempt','t_mtr_user',array('user_id'=>$username),'dblokal');
									$jumlah_salah = $jumlah_salah+1;
									
									$batas_salah = $this->mglobal->showdata('lookup_value','t_mtr_lookup',array('lower(lookup_key)'=>'account_max_attemp'),'dblokal');
									if($jumlah_salah<$batas_salah){
											$this->musers->update_login_attemp($username,$jumlah_salah);
									}
							}
					}
			}
			$data['jumlah_salah'] = $jumlah_salah;
			$data['username'] = $this->input->post('username');
			$data['password'] = $this->input->post('password');

			$this->load->view("login-page",$data); //uncomment jika maintenance dah kelar
			// $this->load->view('f-under-maintenance');
	}

	/* function logout($id = 1){
		
		//$this->session->unset_userdata();
		$this->mglobal->set_is_login(0);
		$this->mcluster->clean_table();
		$this->session->sess_destroy();
		redirect("/login");
	} */
	
	function logout($redirect = '')
	{
		if ($redirect == '') {
			$redirect = '';
		} else {
			$redirect = $redirect;
		}
		
		$this->mglobal->set_is_login(0);
		$this->mcluster->clean_table();
		$this->session->sess_destroy();
		
		redirect('/login/'.$redirect);
	}

	function captcha_check($str)
	{
			if ($this->session->userdata('ratcha') != strtolower($str))
			{
				$this->form_validation->set_message('captcha_check', 'Kode Validasi Salah');
				return FALSE;
			}
			else
			{
				return TRUE;
			}
	}
	
	function password_check($str)
	{
			$allow = $this->mglobal->showdata("is_allowed_time","t_mtr_user",array("user_id"=>$this->input->post('username')),"dblokal");
			$data = array("user_id"=>$this->input->post('username'),
						  "user_password"=>md5($this->input->post('password')));
			
			$istatus = $this->mglobal->showdata('istatus','t_mtr_user',array('user_id'=>$this->input->post('username')),'dblokal');
			//periksa batas kesalahan
			$jumlah_salah = $this->mglobal->showdata('logon_attempt','t_mtr_user',array('user_id'=>$this->input->post('username')),'dblokal');
			$batas_salah = $this->mglobal->showdata('lookup_value','t_mtr_lookup',array('lower(lookup_key)'=>'account_max_attemp'),'dblokal');
			
			//edited by: alfin akhret
			//kode dibawah dipindahkan keatas
			//periksa expired date-nya
			// $last_update_pwd = $this->mglobal->showdata('last_time_change_password','t_mtr_user',array('user_id'=>$this->input->post('username')),'dblokal');
			// $rentang = $this->mglobal->showdata('lookup_value','t_mtr_lookup',array('lower(lookup_key)'=>'account_expired'),'dblokal');
			// $expired_date = date('Y-m-d', strtotime('+'.$rentang.' days', strtotime($last_update_pwd)));

			// //added by : alfin akhret
			// //cari sisa waktu pemakaian password
			// $diff = abs(strtotime(date("Y-m-d")) - strtotime($expired_date));
			// $days = floor($diff/(60*60*24));
			// echo $days;die();
			
			if($istatus <> 1){
					$this->form_validation->set_message('password_check', '<b>Status akun Anda tidak aktif, silakan hubungi Administrator.</b>');
					return FALSE;
			}
			// edited by: alfin akhret
			// validasi password expire date seharusnya dilakukan pada saat semua input sudah benar
			// the code below no longer needed
			// elseif(date("Y-m-d") >= $expired_date ){
			//         $this->form_validation->set_message('password_check', '<b>Maaf, akun Anda telah expired karena tidak mengganti password selama '.$rentang.' hari, silakan hubungi Administrator.</b>');
			//         return FALSE;
			// }
			elseif($jumlah_salah >=$batas_salah){
					$this->form_validation->set_message('password_check', '<b>Maaf, akun Anda telah di-blok karena telah melakukan kesalahan '.$batas_salah.' kali, silakan hubungi Administrator.</b>');
					return FALSE;
			}elseif($allow <> 1){
					$this->form_validation->set_message('password_check', '<b>Anda tidak diizinkan login pada waktu ini.</b>');
					return FALSE;
			}elseif ($this->mglobal->showdata("user_id", "t_mtr_user", $data,"dblokal") == ""){
					$this->form_validation->set_message('password_check', '<b>Username dan/atau Password Anda Salah</b>');
					return FALSE;
			}elseif ($this->mglobal->showdata("is_login", "t_mtr_user", array("user_id"=>$this->input->post('username')),"dblokal") == 1){
					
					//alfin.akhret@gmail.com
					//check last activity
					date_default_timezone_set('Asia/Jakarta');
					$last_activity = $this->mmaster->check_last_activity($this->input->post('username'));

					// $last_activity = strtotime($last_activity[0]->lastActivity);
					$last_activity = strtotime(@$last_activity['lastActivity']);

					//check current time
					$current_time = date('H:i:s');
					$current_time = strtotime($current_time);
					
					// calculate the time interval between last activity and current time

					$interval = ($current_time - $last_activity)/60;
					
					if(($interval > $this->config->item('login_delay_time', 'custom_config')) || ($interval < 0))
					{
						return TRUE;
					}
					else
					{

						$string = "Anda lupa logout pada sesi terakhir atau User dengan ID ini sedang login ditempat lain. <br>Anda hanya bisa login setelah menunggu ".(string)round(($this->config->item('login_delay_time', 'custom_config')-$interval), 1)." menit";

						$this->form_validation->set_message('password_check', $string);
						return FALSE;
					}

			}
			else
			{
					return TRUE;
			}
	}
	

	function capcay(){
		$this->load->view("ratcha/ratcha_image");
		
	}

	/** 
	/* disini fungsi-fungsi yg berhubungan dengan interaksi UX
	/*
	/* @author Alfin akhret <alfin.akhret@gmail.com 
	*/

	/**
	/* check validitas user_id
	/*
	/* @param string user_id
	*/
	function ux_check_user()
	{
		if($this->input->post('user_id') != '')
		{
			$query = $this->musers->ux_check_user($this->input->post('user_id'));
			echo ($query == true)? 'User terdaftar dan aktif' : 'User tidak terdaftar atau tidak aktif';
		}
		else
		{
			echo 'Anda belum mengisi Username';
		}
	}
}